<?php

namespace addons\yunfood\model;

use addons\yunfood\library\Logic;
use addons\yunfood\library\ModelTrait;
use think\Exception;
use think\Model;

/**
 * 防重模型
 */
class Qrcode extends Model
{
    use ModelTrait;

    // 表名,不含前缀
    protected $name = 'yunfood_qrcode';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    protected $resultSetType = 'collection';

    // 类型
    const TYPE_MINI_UNLIMIT = 'mini_unlimit';
    const TYPE_MINI_NORMAL  = 'normal';

    public static function getTypeList()
    {
        return [self::TYPE_MINI_UNLIMIT => __('小程序无限码')];
    }

    public function getTypeTextAttr($value, $data)
    {
        $optionList = self::getTypeList();

        return $optionList[$data['type']] ?? $data['type'];
    }

    // 环境
    const ENV_RELEASE = 'release';
    const ENV_TRIAL   = 'trial';
    const ENV_DEVELOP = 'develop';

    public static function getEnvList()
    {
        return [
            self::ENV_RELEASE => __('正式版'),
            self::ENV_TRIAL   => __('体验版'),
            self::ENV_DEVELOP => __('开发版')
        ];
    }

    /**
     * 获取本地路径
     */
    public function getLocalSrcAttr($value, $data)
    {
        return $data['src'];
    }

    // 页面
    const PAGE_HOME      = 'pages/home/index';
    const PAGE_SHOP_HOME = 'pages/home/index';
    const PAGE_FOOD_HOME = 'pages/food/index';

    /**
     * 获取无限二维码
     *
     * @param $page
     * @param $scene
     * @param false $update
     * @param string $env
     * @return Qrcode
     */
    public static function createMiniQrcode($page, $scene, $update = false, $env = 'release')
    {
        $type = static::TYPE_MINI_UNLIMIT;
        $appId = Config::getGroupAttribute(Config::GROUP_BASE, 'app_id');
        $hash = sha1($appId . $page . $scene . $env);
        $qrcode = self::get(['type' => $type, 'hash' => $hash]);
        if (! $qrcode || $update) {
            // 获取无限二维码
            $response = Logic::getWechatQrcode($page, $scene, [
                'width'       => 600,
                'env_version' => $env,  // release=正式版，trial=体验版，develop=开发版
                'check_path'  => $env === 'release' ? true : false,
//                    'line_color'  => [
//                        'r' => 105,
//                        'g' => 166,
//                        'b' => 134,
//                    ],
            ]);
            if (! $response) {
                throw new Exception('生成小程序二维码失败');
            }

            // 保存二维码到本地
            $fileDir = '/qrcode/' . date('Ym');
            $filePath = ROOT_PATH . 'public/uploads/' . $fileDir;
            $filename = uniqid('', true) . '.jpg';
            if (! is_dir($filePath)) {
                @mkdir($filePath, 0777, true);
            }
            if (! is_really_writable($filePath)) {
                throw new Exception('保存二维码到本地时没有写入权限');
            }
            file_put_contents($filePath . '/' . $filename, $response);

            // 保存二维码到数据库
            if ($qrcode == null) {
                $qrcode = new self();
                $qrcode['type'] = $type;
                $qrcode->hash = $hash;
                $qrcode['data'] = json_encode(compact('page', 'scene', 'env'));
            }
            $qrcode->src = '/uploads' . $fileDir . '/' . $filename;
            $qrcode->save();
        }

        return $qrcode;
    }

    /**
     * 获取普通二维码
     *
     * @param $content
     * @param false $update
     * @return Qrcode
     * @throws Exception
     * @throws \Endroid\QrCode\Exception\InvalidPathException
     */
    public static function createNormalQrcode($content, $update = false)
    {
        $type = static::TYPE_MINI_NORMAL;
        $hash = sha1($content);
        $qrcode = self::get(['type' => $type, 'hash' => $hash]);
        if (! $qrcode || $update) {
            if (! $config = get_addon_config('qrcode')) {
                throw new Exception('还没有安装"二维码生成"插件(免费)');
            }
            $data['text'] = $content;
            $qrCode = \addons\qrcode\library\Service::qrcode($data);

            // 保存二维码到本地
            $fileDir = '/qrcode/' . date('Ym');
            $filePath = ROOT_PATH . 'public/uploads/' . $fileDir;
            $filename = uniqid('', true) . '.jpg';
            if (! is_dir($filePath)) {
                @mkdir($filePath, 0777, true);
            }
            if (! is_really_writable($filePath)) {
                throw new Exception('保存二维码到本地时没有写入权限');
            }
            $qrCode->writeFile($filePath . '/' . $filename);

            // 保存二维码到数据库
            if ($qrcode == null) {
                $qrcode = new self();
                $qrcode['type'] = $type;
                $qrcode->hash = $hash;
                $qrcode['data'] = $content;
            }
            $qrcode->src = '/uploads' . $fileDir . '/' . $filename;
            $qrcode->save();
        }

        return $qrcode;
    }
}
